(() => {
  //vue逻辑代码块
  //
  // 创建 Vue 实例并挂载到 id 为 main 的元素上
  new Vue({
    el: "#main",
    mixins: [mixin],
    data: {
      // 定义数据
      // 所有父级别检查项
      inspectionLevel1: [
        //   {
        // 	"inspectionItemInfoId":"int //检查项主键ID",
        //   "name":"string //检查项名称",
        //   "enName":"string //检查项英文名称",
        //   "inspectionLevel":"string //检查项所属级别 1-一级别; 2-二级别",
        //   "parentInspectionItemInfoId":"int //父检查项id 0-无父检查项,即一级检查项",
        //   "createdDate":"date",
        //   "createdBy":"string",
        //   "updatedDate":"date",
        //   "updatedBy":"string"
        // }, 
      ],
      // 当前模态框的检查项列表
      inspectionLevel2: [],
      inspectionLevel2Title: "",
      isFirst: true,
      // 已经添加检查项信息列表
      haveAddInspectionList: [],
      InspectionDataList: [],
      toDelInspection:"",
      addInspeciont: {
        doctorInfoId: "",//int //医生主键【必须】",
        patientInfoId: "",//int //病患主键【必须】",
        patientInspectionItemCreateArgList: [
          // {
          //   inspectionItemInfoId:"",//int //检查项主键【必须】",
          //   parentInspectionItemInfoId:"",//int //父检查项主键【必须】",
          //   "value:"",//string //检查结果【必须】",
          //   "checkedDate:"",//date //检查时间【必须】"
          // }
        ],
        createdBy: "",//string //创建人",
        updatedBy: "",//string //更新人"
        setTimeList: [],
      },
      forMaxMinCheckList:[],
      CheckDataName:'',
      CheckText:"",
      showPickerVisible:false,
      currentDate:"",
      pickerIndex:""
    },
    created () {
      toastr.options = {
        positionClass: 'toast-top-center'
      };
      // 初始化页面 需要获取当前医生信息
      // new VConsole()
      let url_ = window.location.href
      let data = this.getUrlParams(url_)
      if(Object.keys(data).length){ 
        // 如果已经
        // 更新一下患者id方便切换页面做 病人信息查询
        sessionStorage.setItem("patientInfoId", data.patientInfoId)
        // 更新医生信息
        let doctorTestData = {
          doctorId: data.doctorId,
          doctorInfoId: data.doctorInfoId,
          doctorName: data.doctorName,
          doctorType: data.doctorType,
          hospitalInfoId: data.hospitalInfoId
        }
        sessionStorage.setItem("doctorTestData",JSON.stringify(doctorTestData))
        this.initData()

        // 页面加载完成后执行的方法
        // this.getInspectionData();
        this.getInspectionData({ inspectionLevel: 1, parentInspectionItemInfoId: 0 })
        this.getAllPatientList()
        this.getInspectionDataList()
        }else{
          this.initData()

        // 页面加载完成后执行的方法
        // this.getInspectionData();
        this.getInspectionData({ inspectionLevel: 1, parentInspectionItemInfoId: 0 })
        this.getAllPatientList()
        this.getInspectionDataList()
      }
      
    },
    methods: {
      // 显示选择器
      showPicker (item,index) {
        this.maxDate = this.getTodayEnd()
        this.pickerIndex = index; // 设置选择器下表
        this.currentDate = item.checkedDate ? dayjs(item.checkedDate).toDate() : "" ;
        this.showPickerVisible = true; // 显示选择器
      },
      onConfirm(value){
        // 根据下表更新对应位置的时间
        this.inspectionLevel2[this.pickerIndex].checkedDate = dayjs(value).format('YYYY-MM-DD HH:mm:ss')
        this.checkedDateChange(this.inspectionLevel2[this.pickerIndex], this.pickerIndex)
        this.showPickerVisible = false; // 关闭选择器
      },
      checkedDateChange (t, index) {
        // this.patientInfo.admissionTime
        if(t.checkedDate){
           const isAntibioticValid = dayjs(t.checkedDate).isAfter(dayjs(this.patientInfo.firstIcuAdmissionTime).subtract(24, 'hour'))
          if(!isAntibioticValid){
            // 判断 检查项时间 是否在 入院时 之后
            toastr.error('检查项时间在患者入ICU前24小时之后！');
            // return
          }
        }
        this.setTimeList.includes(t.enName) ? "" : this.setTimeList.push(t.enName)
         // 判断是否第一次选择
         if (this.setTimeList.length  < 2) {
          // 循环
          this.inspectionLevel2 = this.inspectionLevel2.map((item, i) => {
            if (i >= index) {
              item.checkedDate =  t.checkedDate
            }
            return item
          })
        }
      },
      // 新增患者检查项信息  
      addPatientInspeciont () {
        // 对list做必填校验处理
        // 处理保存参数对象
        // "inspectionItemInfoId":"int //检查项主键【必须】",
        // "parentInspectionItemInfoId":"int //父检查项主键【必须】",
        // "value":"string //检查结果【必须】",
        // "checkedDate":"date //检查时间【必须】
        // 如果检查结果有值 时间必填，每值则不校验
        console.log(this.inspectionLevel2)
        this.addInspeciont.patientInspectionItemCreateArgList = []
        this.forMaxMinCheckList = []
        this.CheckDataName = ""
        try {
          this.inspectionLevel2.map((element) => {
            if (element.name === "收缩压/舒张压" && element.value1 && element.value2 && !element.checkedDate) {
              toastr.error("请选择测量" + element.name + "时间")
              throw new Error("中断");
            }
            if (element.name !== "收缩压/舒张压" && element.value && !element.checkedDate) {
              toastr.error("请选择测量" + element.name + "时间")
              throw new Error("中断");
            }
            // if (!element.checkedDate) {
            //   toastr.error("请输入" + element.name + "时间")
            //   throw new Error("中断");
            // }
            // 如果所有都满足
            if(element.name == "收缩压/舒张压" && element.value1 && element.value2 ){
              // 高压 低压 a/b
              let LM = element.minValue.split("/").map(Number)
              let TM = element.maxValue.split("/").map(Number)
              this.forMaxMinCheckList.push({
                haspass:element.haspass ?? false,
                value1:+element.value1,
                value2:+element.value2,
                Lmax:+LM[0],
                Lmin:+LM[1],
                Tmax:+TM[0],
                Tmin:+TM[1],
                name:element.name,
                // 
                inspectionItemInfoId: element.inspectionItemInfoId,
                parentInspectionItemInfoId: element.parentInspectionItemInfoId,
                checkedDate: dayjs(element.checkedDate).format('YYYY-MM-DD HH:mm:ss'),
                value: element.name == "收缩压/舒张压" ? element.value1 + "/" + element.value2 : element.value
              })  
              // this.addInspeciont.patientInspectionItemCreateArgList.push(
              //   {
              //     inspectionItemInfoId: element.inspectionItemInfoId,
              //     parentInspectionItemInfoId: element.parentInspectionItemInfoId,
              //     checkedDate: dayjs(element.checkedDate).format('YYYY-MM-DD HH:mm:ss'),
              //     value: element.name == "收缩压/舒张压" ? element.value1 + "/" + element.value2 : element.value
              //   }
              // )
            }else if(element.value){
              // 增加大小事范围判断确认当前输入内容是否在max-mix范围内
              this.forMaxMinCheckList.push({
                haspass:element.haspass ?? false,
                max:+element.maxValue,
                min:+element.minValue,
                name:element.name,
                inspectionItemInfoId: element.inspectionItemInfoId,
                parentInspectionItemInfoId: element.parentInspectionItemInfoId,
                checkedDate: dayjs(element.checkedDate).format('YYYY-MM-DD HH:mm:ss'),
                value: +element.value
              })
              // this.addInspeciont.patientInspectionItemCreateArgList.push(
              //   {
              //     inspectionItemInfoId: element.inspectionItemInfoId,
              //     parentInspectionItemInfoId: element.parentInspectionItemInfoId,
              //     checkedDate: dayjs(element.checkedDate).format('YYYY-MM-DD HH:mm:ss'),
              //     value: element.value
              //   }
              // )
            }
            
          });
        } catch (error) {
          console.log(error)
          return
        }
        // 在这里在做是否满足大小值范围校验
        try {
          this.forMaxMinCheckList.map(item => {
            if (item.name !== "收缩压/舒张压" && item.name != "意识水平" && (item.value > item.max || item.value < item.min) && !item.haspass) {
              // toastr.error(item.name + "数值超出一般范围（" + item.min +"-" + item.max + "）,是否需要修改！")
              this.CheckDataName = item.name
              this.CheckText = item.name + "数值"+ item.value +"超出一般范围（" + item.min +"," + item.max + "）,是否需要修改！"
              // 整合报错信息 弹出弹层 提示是否继续提交
              $('#confirmModaldelGoOn').modal('show');
              throw new Error("中断");
              // Lmax 30,Tmax 250, Lmin 10,Tmin 130
            } else if(item.name == "收缩压/舒张压" && !item.haspass && ((item.value1 > item.Tmax || item.value1 < item.Lmax) || (item.value2 > item.Tmin || item.value2 < item.Lmin))){
              // 收缩压/舒张压中存在不符合范围的数据
              this.CheckDataName = item.name
              this.CheckText = item.name + "范围("+ item.value1+","+item.value2 +")超出一般范围(" + item.Lmax +"/" + item.Lmin+ ")-("+ item.Tmax +"/" + item.Tmin+"),是否需要修改！"
              // 整合报错信息 弹出弹层 提示是否继续提交
              $('#confirmModaldelGoOn').modal('show');
              throw new Error("中断");
            }
          })
        } catch (error) {
          return
        }
        // return
        // 如果所有的输入内容都满足则直接走提交流程
        $('#inspectionLevel1Modal').modal('hide');
        this.toAdd()
      },
      toAdd(){
        this.addInspeciont.patientInspectionItemCreateArgList = this.forMaxMinCheckList.map(item => {
          return{
            inspectionItemInfoId: item.inspectionItemInfoId,
            parentInspectionItemInfoId: item.parentInspectionItemInfoId,
            checkedDate: item.checkedDate,
            value: item.value
          }
        })
        if(this.addInspeciont.patientInspectionItemCreateArgList.length>1){
          // 判断第一个和最后一个的日期之间是否超过了 15 天
          let firstTime = this.addInspeciont.patientInspectionItemCreateArgList[0].checkedDate
          let lastTime = this.addInspeciont.patientInspectionItemCreateArgList[this.addInspeciont.patientInspectionItemCreateArgList.length - 1].checkedDate
          const diffInDays = dayjs(lastTime).diff(firstTime, 'day');
          if (Math.abs(diffInDays) > 15) {
            toastr.error("第一个生化和最后一个生化数据时间之间不超过15天！")
            return
          } 
        }
        // doctorInfoId:"",//int //医生主键【必须】",
        //   patientInfoId:"",//int //病患主键【必须】",
        const doctorData = sessionStorage.getItem("doctorTestData")
        const { doctorInfoId } = JSON.parse(doctorData)
        const patientInfoId = sessionStorage.getItem("patientInfoId")
        this.addInspeciont.doctorInfoId = doctorInfoId
        this.addInspeciont.patientInfoId = patientInfoId
        const URL = "/patient/inspection/item/add";
        fetch(apiUrl + URL, {
          method: "POST",
          headers: {
            "Content-Type": "application/json",
          },
          body: JSON.stringify(this.addInspeciont)
        })
          .then((response) => {
            return response.json();
          })
          .then((data) => {
            if (data.code === 200) {
              // 刷新设置信息 
              $('#inspectionLevel1Modal').modal('hide');
              this.getInspectionDataList()
            } else {
              toastr.error(data.msg ? data.msg : "操作失败！")
              console.error(data.msg);
            }
          })
          .catch((error) => {
            console.error(error);
          });
      },
      // 去修改
      toEdit(){
        // 直接关闭当前弹层即可 
        $('#confirmModaldelGoOn').modal('hide');
      },
      // 无须修改
      continueSubmit(){
        // 继续提交则把 上一个做标记 为无须修改 然后继续判断下一个是否在范围内 如果不在则继续弹出当前弹层 知道 所有都通过 直接做提交操作
        this.forMaxMinCheckList = this.forMaxMinCheckList.map(item =>{
          if(item.name == this.CheckDataName){
            return {
              ...item,
              haspass:true
            }
          }else{
            return{
              ...item,
            }
          }
        })
        try {
          this.forMaxMinCheckList.map((item,index) => {
            if (item.name != "收缩压/舒张压" && item.name != "意识水平" && (item.value > Number(item.max) || item.value < Number(item.min)) && !item.haspass) {
              // toastr.error(item.name + "数值超出一般范围（" + item.min +"-" + item.max + "）,是否需要修改！")
              this.CheckDataName = item.name
              this.CheckText = item.name + "数值"+ item.value +"超出一般范围（" + item.min +"-" + item.max + "）,是否需要修改"
              // 整合报错信息 弹出弹层 提示是否继续提交
              $('#confirmModaldelGoOn').modal('show');
              throw new Error("中断");
            } else if(item.name == "收缩压/舒张压"  && !item.haspass && ((item.value1 > item.Tmax || item.value1 < item.Lmax) || (item.value2 > item.Tmin || item.value2 < item.Lmin))){
              // 收缩压/舒张压中存在不符合范围的数据
              this.CheckDataName = item.name
              this.CheckText = item.name +  "范围("+ item.value1+","+item.value2 +")超出一般范围(" + item.Lmax +"/" + item.Lmin+ ")-("+ item.Tmax +"/" + item.Tmin+"),是否需要修改！"
              // 整合报错信息 弹出弹层 提示是否继续提交
              $('#confirmModaldelGoOn').modal('show');
              throw new Error("中断");
            }
          })
        } catch (error) {
          return
        }
        $('#confirmModaldelGoOn').modal('hide');
        this.toAdd()
      },
      // 检查项删除 
      inspectiondel (e) {
        // 删除检查项 后刷新检查项列表
        // 
        this.toDelInspection = e
        $('#confirmModaldel').modal('show');

      },
      todel(){
        const URL = "/patient/inspection/item/delete";
        fetch(apiUrl + URL, {
          method: "DELETE",
          headers: {
            "Content-Type": "application/json",
          },
          body: JSON.stringify([this.toDelInspection.patientInspectionItemInfoId])
        })
          .then((response) => {
            return response.json();
          })
          .then((data) => {
            if (data.code === 200) {
              $('#confirmModaldel').modal('hide');
              toastr.success(data.msg ? data.msg : "删除成功！")
              this.getInspectionDataList()
            } else {
              console.error(data.msg);
            }
          })
          .catch((error) => {
            console.error(error);
          });
      },
      // 获取病患设置的检查项详情 
      getInspectionDataList () {
        const patientInfoId = sessionStorage.getItem("patientInfoId")
        const URL = "/patient/inspection/item/detail?patientInfoId=" + patientInfoId;
        fetch(apiUrl + URL, {
          method: "POST",
          headers: {
            "Content-Type": "application/json",
          },
          body: JSON.stringify({
            patientInfoId: patientInfoId
          })
        })
          .then((response) => {
            return response.json();
          })
          .then((data) => {
            if (data.code === 200) {
              this.InspectionDataList = data?.data?.patientInspectionItemDetailList ?? []
            } else {
              console.error(data.msg);
            }
          })
          .catch((error) => {
            console.error(error);
          });
      },
      // checkedDateChange (e, t, index) {
      //   // this.patientInfo.admissionTime
      //   if(t.checkedDate){
      //     if(dayjs(this.patientInfo.admissionTime).isAfter(dayjs(t.checkedDate))){
      //       // 判断 检查项时间 是否在 入院时 之后
      //       toastr.error('检查项时间必须在患者入院时间之后！');
      //       return
      //     }
      //   }
      //   this.setTimeList.includes(t.enName) ? "" : this.setTimeList.push(t.enName)
      //    // 判断是否第一次选择
      //    if (this.setTimeList.length  < 2) {
      //     // 循环
      //     this.inspectionLevel2 = this.inspectionLevel2.map((item, i) => {
      //       if (i >= index) {
      //         item.checkedDate =  t.checkedDate
      //       }
      //       return item
      //     })
      //   }
      // },
      async mesageAdd (data) {
        console.log(data, "一级目录信息")
        this.inspectionLevel2Title = data.name
        this.isFirst = true
        this.setTimeList = []
        let datas = {
          inspectionLevel: 2, parentInspectionItemInfoId: data.inspectionItemInfoId
        }
        await this.getInspectionData(datas)
        $('#inspectionLevel1Modal').modal('show');
      },
      // 切换患者信息 
      changePatient () {
        $('#staticBackdrop').modal('show');
      },
      changePatientHander (item) {
        // 确认选择患者 更新患者信息 并通过患者id查询当前患者基础信息及病症信息
        this.getPaitentDetail(item.patientInfoId)

      },
      getPaitentDetail (patientInfoId) {
        const URL = "/patient/detail?patientInfoId=" + patientInfoId;
        fetch(apiUrl + URL, {
          method: "POST",
          headers: {
            "Content-Type": "application/json",
          },
          // body: JSON.stringify({
          //   patientInfoId: patientInfoId,
          // })
        })
          .then((response) => {
            return response.json();
          })
          .then((data) => {
            if (data.code === 200) {
              // 更新一下患者id方便切换页面做 病人信息查询
              sessionStorage.setItem("patientInfoId", patientInfoId)
              this.patientInfo.patientDiseaseDetailList = []
              Object.assign(this.patientInfo, data.data)
              this.getInspectionData({ inspectionLevel: 1, parentInspectionItemInfoId: 0 })
              this.getInspectionDataList()
              $('#staticBackdrop').modal('hide');
            } else {
              console.error(data.msg);
            }
          })
          .catch((error) => {
            console.error(error);
          });
      },
      // 获取检查项所属级别 1-一级别; 2-二级别【必须】
      // "inspectionLevel":"string //检查项所属级别 1-一级别; 2-二级别【必须】",
      // "parentInspectionItemInfoId":"int //父检查项id 0-无父检查项,即一级检查项【必须】"
      async getInspectionData (data) {
        const URL = "/inspection/item/list";
        await fetch(apiUrl + URL, {
          method: "POST",
          headers: {
            "Content-Type": "application/json",
          },
          body: JSON.stringify(data)
        })
          .then((response) => response.json())
          .then((datas) => {
            console.log(datas, "获取检查项信息列表", data)
            if (datas.code == "200") {
              if (data.inspectionLevel == 1) {
                this.inspectionLevel1 = datas.data ?? []
              } else if (data.inspectionLevel == 2) {
                this.inspectionLevel2 = datas.data ?? []
                this.inspectionLevel2 = this.inspectionLevel2.map(item => {
                  item.value = ""
                  item.value1 = ""
                  item.value2 = ""
                  return item
                })
              }
              console.log(this.inspectionLevel1, this.inspectionLevel2, '12')
            } else {
              console.error("获取检查项信息列表失败！");
            }
          })
          .catch((error) => {
            console.error(error);
          });
      },
    },
  });
})();